<?php
/**
 * Created by IntelliJ IDEA.
 * User: fanxu(fanxu@mufengmc.com)
 * Date: 2017/12/11
 * Time: 15:57
 */
namespace common\models;

/**
 * Class BaseActiveRecord
 * @package common\models
 * @property integer $created_at
 * @property integer $updated_at
 */
class BaseActiveRecord extends \yii\db\ActiveRecord
{
    /**
     * @var bool 是否需要记录表更改日志
     */
    public $needRecordChangeTableLog=false;

    /**
     * @param bool $insert
     * @return bool
     */
    public function beforeSave($insert)
    {
        if ($insert) {
            if ($this->hasAttribute('created_at')) {
                $this->created_at = time();
            }
        }
        if ($this->hasAttribute('updated_at')) {
            $this->updated_at = time();
        }
        return parent::beforeSave($insert); // TODO: Change the autogenerated stub
    }

    /**
     * @param bool $runValidation
     * @param null $attributeNames
     * @return bool
     * @throws \Exception
     */
    public function save($runValidation = true, $attributeNames = null)
    {
        $result = parent::save($runValidation,$attributeNames);
        $this->checkErrors();
        return $result;
    }

    /**
     * @param bool $insert
     * @param array $changedAttributes
     */
    public function afterSave($insert, $changedAttributes)
    {
        $needRecord = false;
        if (!$insert&&!empty($changedAttributes)) {
            $needRecord = true;
        }
        if($this->needRecordChangeTableLog && $needRecord){
            //记录所有改动日志
            $log = new ChangeTableLog();
            $content = [];
            if (!\Yii::$app->user->isGuest) {
                $log->uid = \Yii::$app->user->identity->getId();
                $content['request'] = array_merge(\Yii::$app->request->get(), \Yii::$app->request->post());
            }
            $log->table_name = get_called_class()::tableName();
            $log->row_id = $this->primaryKey;
            $action = \Yii::$app->controller->id.'/'.\Yii::$app->controller->action->id;
            foreach ($changedAttributes as $key => $value) {
                $content['fields'][$key]['old_value'] = $value;
                $content['fields'][$key]['new_value'] = $this->{$key};
            }
            $log->content = json_encode($content);
            $log->action = $action;
            $log->save();
        }
        parent::afterSave($insert, $changedAttributes); // TODO: Change the autogenerated stub
    }

    /**
     * 抛出异常
     * @throws \Exception
     * @return bool
     */
    public function checkErrors()
    {
        $errors = $this->getErrors();
        if(empty($errors)){
            return true;
        }
        foreach($errors as $key => $error){
            $msg = sprintf('%s保存数据发生异常',static::className());
            if(!empty($error)){
                $msg = $error[0];
            }
            throw new \Exception($msg);
        }
    }
}
